/* eslint-disable import/no-unresolved */
/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useState, useCallback, useMemo, useEffect } from 'react';
import {
  Modal,
  Form,
  Input,
  Row,
  Col,
  Select,
  Checkbox,
  Switch,
  Table,
  Button,
  Popconfirm,
  message,
} from 'antd';
import { debounce } from 'lodash';
import { connect } from 'dva';
import { copy } from '@/utils/utils';
import PropTypes from 'prop-types';
import kbBrands from '@kb/brands';
import KeyWordsInput from './KeyWords';
import OpenTime from './OpenTime';
import styles from './styles.less';

const FormItem = Form.Item;
const { Option } = Select;

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 6 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 18 },
  },
};

// 下线扫描
const initScanOptions = [
  {
    key: 1,
    value: '不上传',
  },
  {
    key: 2,
    value: '本级网点扫派件',
  },
  {
    key: 3,
    value: '本级网点扫发件',
  },
  {
    key: 4,
    value: '本级网点扫发件，下级网点扫到件',
  },
  {
    key: 5,
    value: '本级网点扫发件，下级网点扫到件、派件',
  },
  {
    key: 6,
    value: '本级网点扫发件，下级网点扫派件',
  },
];

const thirdCodeConfig = [
  {
    field: 'one_code',
    name: '第一段码',
    rules: [
      {
        max: 20,
        message: '最长不超过20位',
      },
    ],
    placeholder: '请输入第一段码',
  },
  {
    field: 'two_code',
    name: '第二段码',
    rules: [
      {
        max: 20,
        message: '最长不超过20位',
      },
    ],
    placeholder: '请输入第二段码',
  },
  {
    field: 'three_code',
    name: '第三段码',
    rules: [
      {
        max: 20,
        message: '最长不超过20位',
      },
    ],
    placeholder: '请输入第三段码',
  },
];

// 异常格口名称，下拉选项值
const abnormalGridNameOptions = [
  {
    key: '0',
    value: '综合异常口',
  },
  {
    key: '1',
    value: '拦截/通缉异常口',
  },
  {
    key: '2',
    value: '代收/到付异常口',
  },
];

const getBrandName = brand => {
  const { short_name: shortName } = kbBrands.filter(i => i.code === brand)[0] || {};
  return shortName;
};

const modalConfig = isNormal => ({
  sortLine: {
    title: {
      add: '新增分拣线',
      edit: '编辑分拣线',
      authCode: '管理授权码',
    },
    onSaveEffects: {
      add: 'automatic/addSortLine',
      check: 'automatic/checkCode',
      edit: 'automatic/addSortLine',
    },
  },
  grid: {
    title: {
      add: isNormal ? '新增正常口' : '新增异常口',
      edit: isNormal ? '编辑正常口' : '编辑异常口',
    },
    onSaveEffects: {
      add: isNormal ? 'automatic/addGrid' : 'automatic/addAbnormalGrid',
      check: 'automatic/checkCode',
      edit: isNormal ? 'automatic/addGrid' : 'automatic/addAbnormalGrid',
    },
  },
});

const CommonModal = Form.create()(
  ({
    visible,
    type,
    form,
    dispatch,
    getList,
    record = {},
    onClose,
    loading,
    submitLoading,
    isNormal,
    source,
    gridSortLineList = [],
    brands = [],
    userInfo,
    isOldUser,
  }) => {
    const {
      getFieldDecorator,
      validateFields,
      setFieldsValue,
      getFieldValue,
      getFieldsValue,
      isFieldsTouched,
      setFields,
    } = form;
    const {
      id,
      sorting_line_code: sortingLineCode,
      sorting_line_name: sortingLineName,
      sn_code: snCode,
      sorting_line_type: sortingLineType,
      brand,
      up_scanner: upScanner,
      down_scanner: downScanner,
      status,
      grid_code: gridCode,
      grid_name: gridName,
      sorting_line_id: sortingLineId,
      branch_code: branchCode,
      lower_node_dispatch: lowerNodeDispatch,
      down_scanner_object: downScannerObject,
      down_scanner_type: downScannerType,
      one_code: oneCode,
      two_code: twoCode,
      three_code: threeCode,
      error_grid_type: errorGridType,
      addr_keys: addrKeys = '',
      start_plan: startPlan = '',
      line_code,
    } = record;
    const gridAdd = type === 'add' && source === 'grid';
    const gridEdit = type === 'edit' && source === 'grid';
    const [downScanerList, setDownScanerList] = useState([]);
    const [authCodeList, setAuthCodeList] = useState([]);
    const [upDownScanner, setUpDownScanner] = useState([]);
    const [scanOptions, setScanOPtions] = useState(initScanOptions);

    const parsedStartPlan = () => {
      try {
        return JSON.parse(startPlan);
      } catch (error) {
        return [];
      }
    };

    const onCopyClick = useCallback(text => {
      copy(text, copied => {
        if (copied) {
          message.success('复制成功！');
        } else {
          message.warning('复制失败，请手动复制！');
        }
      });
    }, []);

    const title = useMemo(() => modalConfig(isNormal)[source].title[type], [
      type,
      isNormal,
      source,
    ]);

    const onCancelAuth = useCallback(
      cancelId => {
        dispatch({
          type: 'automatic/cancelAuthCode',
          payload: {
            id: cancelId,
          },
        }).then(() => {
          dispatch({
            type: 'automatic/getAuthCodeList',
          }).then(res => {
            setAuthCodeList(res);
          });
        });
      },
      [dispatch],
    );

    const columns = useMemo(
      () => [
        {
          dataIndex: 'token',
          key: 'token',
          title: '授权码',
          width: 200,
          align: 'center',
          render: text => (
            <span>
              {text} <a onClick={() => onCopyClick(text)}>复制</a>
            </span>
          ),
        },
        {
          dataIndex: 'type',
          key: 'type',
          title: '授权对象',
          width: 100,
          align: 'center',
        },
        {
          dataIndex: 'gbt_no',
          key: 'gbt_no',
          title: '供包台编号',
          width: 120,
          align: 'center',
        },
        {
          dataIndex: 'auth_time',
          key: 'auth_time',
          title: '授权日期',
          width: 200,
          align: 'center',
        },
        {
          title: '操作',
          width: 100,
          align: 'center',
          render: (_, data) => (
            <Popconfirm title="确定取消该授权？" onConfirm={() => onCancelAuth(data.id)}>
              <a>取消授权</a>
            </Popconfirm>
          ),
        },
      ],
      [onCancelAuth, onCopyClick],
    );

    const validator = useCallback(
      async (rule, value, callback) => {
        const numTest = /^[0-9]*$/;
        const isNum = numTest.test(value);
        if (!value) {
          callback();
          return;
        }
        const maxLength = value.length > 2;
        if (!isNum) {
          callback('请输入数字');
          return;
        }
        if (maxLength) {
          callback('最长不超过两位');
          return;
        }
        // 编辑时，自身分拣线编号不校验
        if (value === sortingLineCode) {
          callback();
          return;
        }
        const { passed, msg } = await dispatch({
          type: modalConfig().sortLine.onSaveEffects.check,
          payload: {
            sorting_line_code: value,
          },
        });
        if (!passed) {
          callback(msg);
        }
        callback();
      },
      [dispatch, sortingLineCode],
    );

    const operatorValidator = useCallback(
      (rule, value, callback) => {
        const scanValue = getFieldValue('down_scanner_type');
        if (scanValue !== 1 && !value) {
          callback('请选择下节点操作对象');
        }
        callback();
      },
      [getFieldValue],
    );

    const nextSenderValidator = useCallback(
      (rule, value, callback) => {
        const scanValue = getFieldValue('down_scanner_type');
        if (scanValue === 5 && !value) {
          callback('请选择下一站派件员');
        }
        callback();
      },
      [getFieldValue],
    );

    const onSubmit = useCallback(
      () => {
        if (type === 'authCode' || !isFieldsTouched()) {
          onClose();
          return;
        }
        validateFields(async (err, values) => {
          const { addr_keys: formAddrKeys = [], start_plan: formStartPlan = [] } = values;

          if (err) return;
          const payload = { ...values, addr_keys: formAddrKeys.join('、') };
          if (type === 'edit') {
            payload.id = id;
          }
          if (source === 'sortLine') {
            payload.status = values.status ? 2 : 1;
            payload.brand = values.brand.join(',');
            payload.sorting_line_code = `${userInfo.phone}_${payload.sorting_line_code}`;
            payload.start_plan = JSON.stringify(formStartPlan.map(i => i || ''));
          }
          dispatch({
            type: modalConfig(isNormal)[source].onSaveEffects[type],
            payload,
          }).then(res => {
            const { code, msg } = res;
            if (code > 0) {
              message.error(msg);
              return;
            }
            message.success(msg);
            getList();
            onClose();
          });
        });
      },
      [
        getList,
        validateFields,
        onClose,
        source,
        isNormal,
        dispatch,
        type,
        id,
        setFields,
        userInfo,
        isFieldsTouched,
      ],
    );

    const onBrandChange = useCallback(
      value => {
        if (source === 'grid') {
          const { sorting_line_id: formSortingLineId } = getFieldsValue();
          if (!value) {
            setFields({
              branch_code: {
                value: undefined,
              },
            });
            return;
          }

          if (isNormal) {
            setFieldsValue({
              down_scanner_object: undefined,
              down_scanner_type: undefined,
            });
            setDownScanerList([]);
            setScanOPtions(prevState => {
              if (value === 'all') {
                return prevState.filter(i => [1, 2].includes(i.key));
              }
              return initScanOptions;
            });
          }
          // 全品牌不去获取网点编号
          if (value === 'all') {
            setFields({
              branch_code: {
                value: '',
              },
            });
          } else {
            dispatch({
              type: 'automatic/getInnNum',
              payload: {
                brand: value,
                sorting_line_id: formSortingLineId,
              },
            }).then(code => {
              if (!code) {
                setFields({
                  branch_code: {
                    value: undefined,
                    errors: [
                      new Error(`请维护${getBrandName(value)}品牌分拣线默认上线扫描员网点编号`),
                    ],
                  },
                });
              } else {
                setFields({
                  branch_code: {
                    value: code,
                  },
                });
              }
            });
          }
        }
      },
      [dispatch, setFields, source, getFieldsValue, setFieldsValue, isNormal],
    );

    const onScannerChange = useCallback(
      (scanType, firstIn) => {
        const {
          brand: selectBrand,
          branch_code: selectBranchCode,
          sorting_line_id,
        } = getFieldsValue();
        // 获取下节点操作对象
        if (scanType !== 1) {
          dispatch({
            type: 'automatic/getSubOperator',
            payload: {
              down_scanner_type: scanType,
              brand: selectBrand || brand,
              branch_code: selectBranchCode || branchCode,
              sorting_line_id,
            },
          }).then(res => {
            setDownScanerList(res);
          });
        } else {
          setDownScanerList([]);
        }
        // 编辑时需要清空
        if (!firstIn) {
          setFieldsValue({
            down_scanner_object: undefined,
          });
        }
      },
      [dispatch, getFieldsValue, setFieldsValue, brand, branchCode],
    );

    const onSortLineChange = useCallback(
      () => {
        if (source === 'grid') {
          setFieldsValue({
            brand: undefined,
            branch_code: undefined,
            down_scanner_object: undefined,
            down_scanner_type: undefined,
          });
          setDownScanerList([]);
        }
      },
      [source, setFieldsValue],
    );

    const onAddAuthCode = useCallback(
      debounce(
        () => {
          dispatch({
            type: 'automatic/addAuthCode',
          }).then(() => {
            dispatch({
              type: 'automatic/getAuthCodeList',
            }).then(res => {
              setAuthCodeList(res);
            });
          });
        },
        300,
        {
          trailing: false,
          leading: true,
        },
      ),
      [],
    );

    const onSortingLineTypeChange = (value, cleanBrand = true) => {
      // 出港有效的品牌
      const enableBrand = ['zt', 'ht', 'yt'];
      if (value === '2' && cleanBrand) {
        setFieldsValue({
          brand: [],
        });
      }

      brands.forEach(val => {
        if (!enableBrand.includes(val.brand) && value === '2') {
          val.disabled = true;
        } else {
          val.disabled = false;
        }
      });
      dispatch({
        type: 'automatic/save',
        payload: {
          sortLineBrands: brands,
        },
      });
    };

    const AuthCodeContent = useMemo(
      () => ({ onClick }) => (
        <>
          <Button onClick={onClick} style={{ marginBottom: 10 }} type="primary">
            获取授权码
          </Button>
          <Table
            rowKey="id"
            columns={columns}
            dataSource={authCodeList}
            loading={loading}
            pagination={false}
          />
        </>
      ),
      [authCodeList, columns, loading],
    );

    const gridFormContent = useMemo(
      () => {
        const codeMap = {
          one_code: oneCode,
          two_code: twoCode,
          three_code: threeCode,
        };
        const { down_scanner_type: formDownScannerType, brand: formBrand } = getFieldsValue();
        return () => (
          <>
            <FormItem label="分拣线">
              {getFieldDecorator('sorting_line_id', {
                initialValue:
                  type === 'edit' ? sortingLineId : gridSortLineList[0] && gridSortLineList[0].id,
                rules: [
                  {
                    required: true,
                    message: '请维护分拣线编号',
                  },
                ],
              })(
                <Select placeholder="请选择分拣线" onChange={onSortLineChange}>
                  {gridSortLineList.map(v => (
                    <Option value={v.id} key={v.id}>
                      {v.sorting_line_name}
                    </Option>
                  ))}
                </Select>,
              )}
            </FormItem>
            <FormItem label="快递品牌">
              {getFieldDecorator('brand', {
                initialValue: isNormal && type === 'add' ? 'sto' : brand,
                rules: [
                  {
                    required: isNormal,
                    message: '请选择快递品牌',
                  },
                ],
              })(
                <Select
                  allowClear={!isNormal}
                  placeholder="请选择快递品牌"
                  onChange={onBrandChange}
                >
                  {brands.filter(i => i.brand !== '0').map(val => (
                    <Option key={val.brand} value={val.brand}>
                      {val.name}
                    </Option>
                  ))}
                </Select>,
              )}
            </FormItem>
            <FormItem label="网点编号">
              {getFieldDecorator('branch_code', {
                initialValue: branchCode,
                rules: [
                  {
                    required: isNormal && formBrand !== 'all',
                    message: '请选择品牌后，再获取网点编号',
                  },
                ],
              })(<Input disabled />)}
            </FormItem>
            <FormItem label="格口编号">
              {getFieldDecorator('grid_code', {
                initialValue: gridCode,
                rules: [
                  {
                    max: 5,
                    message: '格口编号最长不超过5位',
                  },
                  {
                    pattern: /^[0-9a-zA-Z]+$/,
                    message: '格口编号仅限输入英文和数字',
                  },
                  {
                    required: true,
                    message: '请维护格口编号',
                  },
                ],
              })(<Input placeholder="请输入格口编号" />)}
            </FormItem>
            {isNormal ? (
              <FormItem label="格口名称">
                {getFieldDecorator('grid_name', {
                  initialValue: gridName,
                  rules: [
                    {
                      max: 50,
                      message: '名称最长不超过50位字符',
                    },
                    {
                      required: true,
                      message: '请维护格口名称',
                    },
                  ],
                })(<Input placeholder="请输入格口名称" />)}
              </FormItem>
            ) : (
              <FormItem label="格口名称">
                {getFieldDecorator('error_grid_type', {
                  initialValue: errorGridType,
                  rules: [
                    {
                      required: true,
                      message: '请维护格口名称',
                    },
                  ],
                })(
                  <Select placeholder="请选择格口名称" allowClear>
                    {abnormalGridNameOptions.map(val => (
                      <Option key={val.key} value={val.key}>
                        {val.value}
                      </Option>
                    ))}
                  </Select>,
                )}
              </FormItem>
            )}

            {isNormal && (
              <>
                <FormItem label="下线扫描">
                  {getFieldDecorator('down_scanner_type', {
                    initialValue: type === 'edit' ? downScannerType * 1 : undefined,
                    rules: [
                      {
                        required: true,
                        message: '请维护下线扫描类型',
                      },
                    ],
                  })(
                    <Select placeholder="请选择下线扫描" onChange={e => onScannerChange(e, false)}>
                      {scanOptions.map(val => (
                        <Option key={val.key} value={val.key}>
                          {val.value}
                        </Option>
                      ))}
                    </Select>,
                  )}
                </FormItem>
                <FormItem label="下节点操作对象">
                  {getFieldDecorator('down_scanner_object', {
                    initialValue: downScannerObject,
                    rules: [
                      {
                        validator: operatorValidator,
                      },
                      {
                        required: formDownScannerType !== 1,
                        message: '请维护下节点操作对象',
                      },
                    ],
                  })(
                    <Select
                      allowClear
                      showSearch
                      optionFilterProp="children"
                      placeholder="请选择下节点操作对象"
                      disabled={formBrand === 'all' && formDownScannerType === 1}
                      filterOption={(input, option) =>
                        option.props.children
                          .toLocaleString()
                          .toLowerCase()
                          .indexOf(input.toLowerCase()) >= 0
                      }
                    >
                      {/* 本级网点扫发件，渲染网点信息，其余的渲染业务员信息 */}
                      {formDownScannerType === 3
                        ? downScanerList.map(val => (
                            <Option key={val.id} value={val.station_code}>
                              {val.station_code}-{val.station_name}
                            </Option>
                          ))
                        : downScanerList.map(val => (
                            <Option key={val.courier_phone} value={val.courier_phone}>
                              {val.courier_name}-{val.courier_phone}
                            </Option>
                          ))}
                    </Select>,
                  )}
                </FormItem>
                {formDownScannerType === 5 && (
                  <FormItem label="下一站派件员">
                    {getFieldDecorator('lower_node_dispatch', {
                      initialValue: lowerNodeDispatch,
                      rules: [
                        {
                          validator: nextSenderValidator,
                        },
                      ],
                    })(
                      <Select allowClear placeholder="请选择下一站派件员">
                        {downScanerList.map(val => (
                          <Option key={val.courier_phone} value={val.courier_phone}>
                            {val.courier_name}-{val.courier_phone}
                          </Option>
                        ))}
                      </Select>,
                    )}
                  </FormItem>
                )}
                {[3, 4, 5, 6].includes(Number(formDownScannerType)) &&
                  formBrand == 'yt' && (
                    <FormItem label="线路号">
                      {getFieldDecorator('line_code', {
                        initialValue: line_code,
                        rules: [
                          {
                            required: true,
                            message: '请维护线路号',
                          },
                        ],
                      })(<Input allowClear placeholder="请选择输入发件线路号" />)}
                    </FormItem>
                  )}
                {thirdCodeConfig.map(val => (
                  <FormItem label={val.name} key={val.field}>
                    {getFieldDecorator(val.field, {
                      initialValue: codeMap[val.field],
                      rules: val.rules,
                    })(<Input placeholder={val.placeholder} />)}
                  </FormItem>
                ))}
                {isOldUser && (
                  <FormItem label="地址关键字">
                    {getFieldDecorator('addr_keys', {
                      initialValue: addrKeys ? addrKeys.split('、').filter(i => i) : [],
                    })(<KeyWordsInput />)}
                  </FormItem>
                )}
              </>
            )}
          </>
        );
      },
      [
        getFieldDecorator,
        isNormal,
        operatorValidator,
        gridSortLineList,
        gridCode,
        gridName,
        sortingLineId,
        branchCode,
        brand,
        type,
        downScannerObject,
        downScannerType,
        oneCode,
        twoCode,
        threeCode,
        onBrandChange,
        onScannerChange,
        downScanerList,
        onSortLineChange,
        lowerNodeDispatch,
        nextSenderValidator,
        errorGridType,
        addrKeys,
        brands,
        isOldUser,
      ],
    );

    const sortLineFormContent = useMemo(
      () => () => (
        <>
          <FormItem label="分拣线">
            {getFieldDecorator('sorting_line_code', {
              initialValue:
                sortingLineCode && sortingLineCode.includes('_')
                  ? sortingLineCode.split('_')[1]
                  : sortingLineCode,
              rules: [
                {
                  required: true,
                  message: '请维护分拣线编号',
                },
                {
                  validator,
                },
              ],
              validateTrigger: 'onSubmit',
            })(<Input addonBefore={`${userInfo.phone}_`} placeholder="请输入分拣编号" />)}
          </FormItem>
          <FormItem label="分拣线名称">
            {getFieldDecorator('sorting_line_name', {
              initialValue: sortingLineName,
              rules: [
                {
                  required: true,
                  message: '请维护分拣线名称',
                },
                {
                  max: 40,
                  message: '名称最长不超过40位字符',
                },
              ],
            })(<Input placeholder="请输入分拣线名称" />)}
          </FormItem>
          <FormItem label="设备SN码">
            {getFieldDecorator('sn_code', {
              initialValue: snCode,
              rules: [
                {
                  max: 50,
                  message: '名称最长不超过50位字符',
                },
              ],
            })(<Input placeholder="请输入设备SN码" />)}
          </FormItem>
          <FormItem label="分拣线功能">
            {getFieldDecorator('sorting_line_type', {
              initialValue: sortingLineType || '1',
              rules: [
                {
                  required: true,
                  message: '请选择分拣线功能',
                },
              ],
            })(
              <Select onChange={onSortingLineTypeChange}>
                <Option value="1" key="1">
                  进港
                </Option>
                <Option value="2" key="2">
                  出港
                </Option>
              </Select>,
            )}
          </FormItem>
          <FormItem label="分拣线品牌">
            {getFieldDecorator('brand', {
              initialValue: brand ? brand.split(',') : [],
              rules: [
                {
                  required: true,
                  message: '请选择分拣线品牌',
                },
              ],
            })(
              <Checkbox.Group style={{ width: '100%' }}>
                <Row>
                  {brands.filter(i => !['all', '0'].includes(i.brand)).map(val => (
                    <Col key={val.brand} span={6}>
                      <Checkbox value={val.brand} key={val.brand} disabled={val.disabled}>
                        {val.name}
                      </Checkbox>
                    </Col>
                  ))}
                </Row>
              </Checkbox.Group>,
            )}
          </FormItem>
          <FormItem label="默认上线扫描员">
            {getFieldDecorator('up_scanner', {
              initialValue: upScanner,
              rules: [
                {
                  required: true,
                  message: '请选择默认上线扫描员',
                },
              ],
            })(
              <Select allowClear placeholder="请选择默认上线扫描员">
                {upDownScanner.map(val => (
                  <Option value={val.courier_phone} key={val.courier_phone}>
                    {`${val.courier_name} - ${val.courier_phone}`}
                  </Option>
                ))}
              </Select>,
            )}
          </FormItem>
          <FormItem label="默认下线扫描员">
            {getFieldDecorator('down_scanner', {
              initialValue: downScanner,
              rules: [
                {
                  required: true,
                  message: '请选择默认下线扫描员',
                },
              ],
            })(
              <Select allowClear placeholder="请选择默认下线扫描员">
                {upDownScanner.map(val => (
                  <Option value={val.courier_phone} key={val.courier_phone}>
                    {`${val.courier_name} - ${val.courier_phone}`}
                  </Option>
                ))}
              </Select>,
            )}
          </FormItem>
          <FormItem label="是否开启">
            {getFieldDecorator('status', {
              valuePropName: 'checked',
              initialValue: status ? status === '2' : true,
            })(<Switch checkedChildren="开" unCheckedChildren="关" />)}
          </FormItem>
          <FormItem label="方案开启时间">
            {getFieldDecorator('start_plan', {
              initialValue: parsedStartPlan() || [],
            })(<OpenTime />)}
          </FormItem>
        </>
      ),
      [
        getFieldDecorator,
        sortingLineName,
        snCode,
        status,
        sortingLineCode,
        brand,
        downScanner,
        upScanner,
        validator,
        upDownScanner,
        brands,
        startPlan,
        sortingLineType,
      ],
    );

    const FormContent = useMemo(
      () => () => (
        <Form {...formItemLayout} className={styles.form}>
          {(gridAdd || gridEdit) && gridFormContent()}
          {source === 'sortLine' && sortLineFormContent()}
        </Form>
      ),
      [gridAdd, gridEdit, source, gridFormContent, sortLineFormContent],
    );

    useEffect(
      () => {
        // 分拣线配置
        if (source === 'sortLine' && visible) {
          if (type === 'add' || type === 'edit') {
            onSortingLineTypeChange(sortingLineType, false);
            dispatch({
              type: 'automatic/getScanner',
            }).then(res => {
              setUpDownScanner(res);
            });
          }
          if (type === 'authCode') {
            dispatch({
              type: 'automatic/getAuthCodeList',
              payload: {
                sorting_line_id: id,
              },
            }).then(res => {
              setAuthCodeList(res);
            });
          }
        }
        // 格口配置，正常口配置
        if (source === 'grid' && visible && isNormal) {
          if (type === 'edit') {
            onScannerChange(downScannerType, true);
          } else if (type === 'add') {
            // 防止获取不到表单信息
            setTimeout(() => {
              const formBrandField = getFieldValue('brand');
              // 获取默认的网点编号
              onBrandChange(formBrandField);
            }, 200);
          }
        }

        if (!visible) {
          setAuthCodeList([]);
          dispatch({
            type: 'automatic/save',
            payload: {
              authCodeList: [],
            },
          });
        }
      },
      [
        type,
        id,
        dispatch,
        visible,
        source,
        downScannerType,
        isNormal,
        sortingLineType,
        onScannerChange,
        onBrandChange,
        getFieldValue,
      ],
    );

    return (
      <Modal
        width={type === 'authCode' ? 768 : 560}
        centered
        onCancel={onClose}
        onOk={onSubmit}
        title={title}
        visible={visible}
        destroyOnClose
        confirmLoading={submitLoading}
      >
        {type === 'authCode' ? <AuthCodeContent onClick={onAddAuthCode} /> : <FormContent />}
      </Modal>
    );
  },
);

CommonModal.propTypes = {
  isNormal: PropTypes.bool, // 是否是异常格口
  visible: PropTypes.bool.isRequired,
  source: PropTypes.oneOf(['grid', 'arrivalSorting', 'gridStatistics', 'sortLine']).isRequired, // 页面类型
  type: PropTypes.oneOf(['add', 'edit', 'authCode']).isRequired, // 弹窗展示类型
  getList: PropTypes.func.isRequired,
  onClose: PropTypes.func.isRequired,
  record: PropTypes.object,
};

export default connect(({ automatic, loading, info }, { source, type, isNormal }) => {
  const { sortLineBrands = [] } = automatic;
  // 异常口过滤全品牌
  const brands = sortLineBrands.filter(i => (isNormal ? i : i.brand !== 'all'));
  return {
    submitLoading: loading.effects[modalConfig(isNormal)[source].onSaveEffects[type]],
    loading: loading.effects['automatic/getAuthCodeList'],
    gridSortLineList: automatic.gridSortLineList,
    brands,
    userInfo: info.companyData.user_info,
  };
})(React.memo(CommonModal));
